OOP Patterns
Table of Contents
1. Methods and Colon Syntax
Tables can have functions.
local account = {
balance = 0,
}
function account.deposit(self, amount)
self.balance = self.balance + amount
end
-- calling methods
account.deposit(account, 100)
print(account.balance) -- 100
We can use the colon syntax to simplify the recipient.
function account:deposit(amount)
self.balance = self.balance + amount
end
account:deposit(100)
2. Metatables
Since Lua does not have built-in class system, prototype-style patterns are commonly used, which involves metatables.
The key role is __index. __index = Account means that when a method is absent from the instancec table, Lua looks for it in __index, in this case, Account.
local Account = {}
Account.__index = Account
function Account.new(owner, balance)
return setmetatable({ owner = owner, balance = balance or 0 }, Account)
end
function Account:deposit(amount)
assert(amount > 0, "Amount must be positive")
self.balance = self.balance + amount
end
function Account:withdraw(amount)
if amount > self.balance then
return nil, "Insufficient deposit"
end
self.balance = self.balance - amount
return true
end
local account = Account.new("Ada", 100)
print(account.balance) -- 100
account:deposit(50)
print(account.balance) -- 150
account:withdraw(120)
print(account.balance) -- 30
2.1. More Metamethods and Metatables
Metatables customize operations on tables and userdata. Important metamethods include:
| Metamethod | Controls |
|---|---|
__index |
missing-field lookup |
__newindex |
assignment to missing fields |
__call |
calling a non-function |
__tostring |
string representation |
__eq, __lt, __le |
comparisons |
__add, __sub, __mul |
arithmetic |
__len |
length |
__pairs |
used in pairs iteration |
__close |
deterministic cleanup |
__gc |
garbage-collection finalization |